package proxy

import (
	// nolint
	"crypto/sha1"
	"strings"

	"github.com/xuender/oils/hashs"
)

// nolint
var execKeys = []string{"UPDATE", "INSERT", "DELETE", "DROP", "TRUNCATE"}

func IsExec(sql string) bool {
	sql = strings.ToUpper(sql)

	for _, key := range execKeys {
		if strings.Contains(sql, key) {
			return true
		}
	}

	return false
}

func NativePassword(password string, salt []byte) []byte {
	if len(password) == 0 {
		return nil
	}

	// stage1Hash = SHA1(password)
	// nolint
	crypt := sha1.New()
	crypt.Write([]byte(password))
	stage1 := crypt.Sum(nil)

	// scrambleHash = SHA1(scramble + SHA1(stage1Hash))
	// inner Hash
	crypt.Reset()
	crypt.Write(stage1)
	stage1SHA1 := crypt.Sum(nil)

	// stage2Hash = SHA1(salt <concat> SHA1(SHA1(password)))
	crypt.Reset()
	crypt.Write(salt)
	crypt.Write(stage1SHA1)
	stage2 := crypt.Sum(nil)

	// srambleHash = stage1Hash ^ stage2Hash
	scramble := make([]byte, len(stage2))
	for i := range stage2 {
		scramble[i] = stage1[i] ^ stage2[i]
	}

	return scramble
}

func FingerID(sql string) uint64 {
	return hashs.SipHashNumber([]byte(Finger(sql)))
}

func ToUpperTrum(sql string) string {
	return strings.ReplaceAll(strings.ToUpper(sql), " ", "")
}
